import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/index',
    name: 'index',
    meta: { title:'index' },
    component: () => import('../views/Index.vue'),
    children:[
      {
        path: '/index/home',
        name: 'home',
        meta: { title:'首页' },
        component: () => import('../views/index/Home.vue')
      },
      {
        path: '/index/tuan',
        name: 'tuan',
        meta: { title:'爆爆团' },
        component: () => import('../views/index/Tuan.vue')
      },
      {
        path: '/index/order',
        name: 'order',
        meta: { title:'订单' },
        component: () => import('../views/index/Order.vue')
      },
      {
        path: '/index/mine',
        name: 'mine',
        meta: { title:'我的' },
        component: () => import('../views/index/Mine.vue')
      },
      {
        path:'/index',
        redirect:'/index/home'
      },
      {
        path:'*',
        component: () => import('../views/NotFound.vue') 
        
      }
    ]
    
  },
  {
    path: '/register',
    name: 'register',
    meta: { title:'注册' },
    component: () => import('../views/Register.vue'),
  },
  {
    path: '/login',
    name: 'about',
    meta: { title:'登陆' },
    component: () => import('../views/Login.vue'),
  },
  {
    // 路由地址中带有 :xxx 的路由地址 都属于动态路由
    // path: '/detail/:name', // :name 是个占位符, 实际在跳路由的时候,会动态拼接参数 例如: '/detail/'+100
    path: '/detail',
    name: 'detail',
    meta: { title:'详情' },
    component: () => import('../views/Detail.vue'),
    
  },
  // 一级路由重定向
  {
    path:'/',
    redirect:'/index'
  },
  // 404路由
  {
    path:'*',
    component: () => import('../views/NotFound.vue') 
    
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to,from,next)=>{
  document.title = to.meta.title;

  var token = localStorage.getItem('token');

  // 只有在登陆以后 才可以跳转到 订单页
  if(to.path == '/index/order' || to.path == '/index/mine'){ 
    //想要跳往 订单页 或者 我的页面
    if( token ){ //已经登陆
      next();
    }else{ //未登录
      next('/login');
    }
  }else{ //其他页面( 非订单页 )
    next();//必须手动调用该函数, 否则无法完成路由跳转
  } 

  
})

export default router
